package com.pwser.provider.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.pwser.common.entities.Dept;
import com.pwser.provider.service.DeptService;

@RestController
public class DeptController {

	@Autowired
	private DeptService deptService;

	@GetMapping(value = "/dept/get/{id}")
	// 一旦调用服务方法失败并抛出了错误信息后，会自动调用@HystrixCommand标注好的fallbackMethod调用类中的指定方法
	@HystrixCommand(fallbackMethod = "processHystrix_Get")
	public Dept get(@PathVariable("id") Long id) {
		Dept dept = deptService.get(id);
		if (null == dept) {
			throw new RuntimeException("该ID：" + id + "没有没有对应的信息");
		}
		return dept;
	}

	public Dept processHystrix_Get(@PathVariable("id") Long id) {
		return new Dept().setDeptNo(id).setDeptName("该ID：" + id + "没有没有对应的信息,null--@HystrixCommand")
				.setDbSource("no this database in MySQL");
	}
	
	//@GetMapping(value = "/dept/get/{id}")
	@HystrixCommand(fallbackMethod = "processHystrix_Get2")
	public Dept get2(@PathVariable("id") Long id) throws Exception {
		Dept dept = deptService.get(id);
		Thread.sleep(10000); //模拟服务调用时间过长
		return dept;
	}

	public Dept processHystrix_Get2(@PathVariable("id") Long id) {
		return new Dept().setDeptNo(null).setDeptName("服务可能崩溃，请联系管理员！").setDbSource(null);
	}

}
